package com.liyiwei.redislock.service.impl;

import com.liyiwei.redislock.entity.ShopEntity;
import com.liyiwei.redislock.mapper.ShopDao;
import com.liyiwei.redislock.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liyiwei.redislock.service.RedisRLockImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyiwei
 * @since 2021-03-09
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopDao, ShopEntity> implements IShopService {
    @Autowired
    private RedisRLockImpl redisRLock;

    @Override
    public void cutDown() {
        ShopEntity shopEntity = this.getById(1);
        Integer count = shopEntity.getCount();
        if (shopEntity.getCount() <= 0){
            System.out.println("商品已经卖完了");
        }else{
            String key = redisRLock.tryLockDefaultByTime("userId.toString()");
            test(shopEntity,key);
            this.updateById(shopEntity);
            System.out.println("抢到编号："+count+ "的票" + "------剩余"+(shopEntity.getCount())+ "张票");
        }
         redisRLock.unLock("userId.toString()",redisRLock.LOCKHASHKEY);
    }

    private void test(ShopEntity shopEntity,String key){
        redisRLock.tryLockDefaultByTime("userId.toString()",key);
        shopEntity.setCount(shopEntity.getCount()-1);
        redisRLock.unLock("userId.toString()",key);
    }
}
